<template>
  <div>
    <Main v-if="shows === 'form'" :type="'form'">
      <Title :title="pageName" />

      <el-form
        ref="form"
        label-width="150px"
        label-position="right"
        :model="form"
        :rules="form"
      >
        <el-form-item
          label="门店名称"
          prop="name"
          :rules="{
            required: true,
            message: '请输入门店名称',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.name"
            class="form-input"
            size="medium"
            placeholder="请输入门店名称"
            style="line-height:20px;"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="门店编号"
          prop="store_number"
          :rules="[
            { required: true, message: '请输入门店编号', trigger: 'blur' },
            { type: 'number', message: '请输入数字', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model.number="form.store_number"
            class="form-input"
            size="medium"
            placeholder="请输入门店编号"
            style="line-height:20px;"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="管理员账号"
          prop="username"
          :rules="{
            required: true,
            message: '请输入管理手机号',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.username"
            class="form-input"
            size="medium"
            :maxlength="11"
            onkeyup='value=value.replace(/\D/g,"")'
            onpaste='value=value.replace(/\D/g,"")'
            oncontextmenu='value=value.replace(/\D/g,"")'
            placeholder="请输入管理手机号"
            @change="inputTagUsername"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="管理员姓名"
          prop="truename"
          :rules="{
            required: true,
            message: '请输入管理员姓名',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.truename"
            class="form-input"
            size="medium"
            placeholder="请输入管理员姓名"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label='门店权限'
                          prop='tag_id'
                          :rules='{ required: true, message: "请选择权限", trigger: "blur" }'>
              <el-select v-model='form.tag_id'
                         placeholder='请选择商品标签'>
                <el-option v-for='item in optionsQX'
                           :key='item.id'
                           :label='item.name'
                           :value='item.id'
                           class="options">
                  <span class='l'>{{ item.name }}</span>
                  <i class='r el-icon-error'
                     @click='delTag(item.id)'
                     v-if='item.type !== 1 '></i>
                </el-option>
              </el-select>
              &emsp;
              <el-button type='text'>刷新</el-button>
              <el-button type='text'>新增门店权限
              </el-button>

            </el-form-item> -->
        <el-form-item
          label="联系电话"
          prop="mobile"
          :rules="{
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.mobile"
            class="form-input"
            size="medium"
            :maxlength="11"
            onkeyup='value=value.replace(/\D/g,"")'
            onpaste='value=value.replace(/\D/g,"")'
            oncontextmenu='value=value.replace(/\D/g,"")'
            placeholder="请输入联系电话"
            @change="inputTagMobile"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="门店状态"
          prop="status"
          :rules="{ required: true, message: '', trigger: 'blur' }"
        >
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">未启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="门店标签">
          <el-select v-model="form.tag_id" placeholder="请选择">
            <el-option
              v-for="item in optionsLabel"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="门店排序"
          prop="sort"
          :rules="{
            required: true,
            message: '请输入门店排序',
            trigger: 'blur'
          }"
        >
          <el-input-number
            v-model="form.sort"
            :min="0"
            :precision="0"
            :controls="false"
            size="medium"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="营业时间"
          prop="open_week"
          :rules="{
            required: true,
            message: '请选择营业时间',
            trigger: 'blur'
          }"
        >
          <el-button @click="dialogVisible = true">{{
            form.open_week.length > 0 ? "修改营业时间" : "添加营业时间"
          }}</el-button>
          <div v-if="!dialogVisible">
            <span v-for="(item, index) in form.open_week" :key="index">
              {{ item == 1 ? "周一 " : "" }}
              {{ item == 2 ? "周二 " : "" }}
              {{ item == 3 ? "周三 " : "" }}
              {{ item == 4 ? "周四 " : "" }}
              {{ item == 5 ? "周五 " : "" }}
              {{ item == 6 ? "周六 " : "" }}
              {{ item == 7 ? "周天 " : "" }}
            </span>
            <div class="timeC">
              <p
                v-for="(item, index) in form.open_time"
                :key="index"
                class="time-chlid"
              >
                {{ item.start }}-{{ item.end }}
              </p>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="地区"
          prop="position"
          :rules="{
            required: true,
            message: '请选择地区',
            trigger: 'blur'
          }"
        >
          <el-cascader
            v-model="form.position"
            :options="options"
            :props="defaultProps"
            class="form-input"
            change-on-select
            @change="cascaderTag"
          ></el-cascader>
        </el-form-item>

        <el-form-item
          label="详细地址"
          prop="address"
          :rules="{
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.address"
            placeholder="请输入内容"
            style="width:50%;"
            size="medium"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchTag"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item
          label="选取地址"
          prop="longitude"
          :rules="{ required: true, message: '请选取地址', trigger: 'blur' }"
        >
          <GDmap
            :type="'Marker'"
            style="margin-top:20px;"
            :datas="{ search: searchs }"
            @retunrData="retunrData"
          />
        </el-form-item>
      </el-form>
      <Footer>
        <el-button plain @click="$emit('out')">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </Footer>

      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        width="40%"
        class="dialogBox"
      >
        <div>
          营业日
        </div>
        <div>
          <el-checkbox-group v-model="form.open_week">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="7">周日</el-checkbox>
          </el-checkbox-group>
        </div>
        <div>
          时间段
        </div>
        <div>
          <el-time-picker
            v-model="form.time"
            is-range
            size="small"
            value-format="HH:mm"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
          <el-button
            size="small"
            :disabled="form.open_time.length >= 3"
            @click="addTime"
            >新增时间段</el-button
          >
          &nbsp;&nbsp; <span style="color:#909399">最多可添加三组</span>
        </div>
        <div class="timeC">
          <p
            v-for="(item, index) in form.open_time"
            :key="index"
            class="time-chlid"
          >
            {{ item.start }}-{{ item.end }}
            <i class="el-icon-delete time-del" @click="timeDel(index)"></i>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </Main>
    <!-- <set v-if="shows === 'set'"
         @out='out'
         @submit='submit' /> -->
  </div>
</template>
<script>
import { ADD_STORE, STORE_TAGLIST } from "../service";
import { THREELEVELLINKAGE } from "@/service/public";

export default {
  components: {
    GDmap: () => import("publicCom/GDmap")
    // set: () => import("./set")
  },
  props: {
    dataMsg: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      pageName: "新建门店",
      form: {
        name: "",
        store_number: "",
        username: "",
        truename: "",
        mobile: "",
        open_week: [],
        time: "",
        open_time: [],
        position: "",
        address: "",
        selectAddress: "",
        province: "",
        city: "",
        area: "",
        longitude: "",
        latitude: "",
        status: 1,
        tag_id: "",
        sort: ""
      },
      shows: "form",
      searchs: "",
      addressJson: {},
      options: [],
      optionsQX: [],
      optionsLabel: [],
      defaultProps: {
        value: "id",
        children: "children",
        label: "name"
      },
      dialogVisible: false
    };
  },
  created() {
    let json = JSON.stringify(this.dataMsg);
    if (json !== "{}") {
      this.pageName = "编辑门店";
      this.form.name = this.dataMsg.name;
      this.form.store_number = parseInt(this.dataMsg.store_number);
      this.form.username = JSON.parse(this.dataMsg.username);
      this.form.truename = this.dataMsg.truename;
      this.form.mobile = JSON.parse(this.dataMsg.mobile);
      this.form.open_week = this.dataMsg.open_week.split(",");
      let arr = this.dataMsg.open_time.split(",");
      arr.forEach(ele => {
        ele = ele.split("-");
        this.form.open_time.push({ start: ele[0], end: ele[1] });
      });
      this.form.longitude = this.dataMsg.latitude;
      this.form.latitude = this.dataMsg.latitude;
      this.form.province = this.dataMsg.province;
      this.form.city = this.dataMsg.city;
      this.form.area = this.dataMsg.area;
      this.form.position = this.dataMsg.position.split(",");
      this.form.address = this.dataMsg.address;
      this.form.selectAddress = this.dataMsg.select_address;
      this.form.status = this.dataMsg.status ? 1 : 0;
      this.form.tag_id = this.dataMsg.tag_id;
    } else {
      this.pageName = "新建门店";
    }
    this.getAddress();
    this.getLabel();
  },

  methods: {
    handleClose() {
      let json = JSON.stringify(this.dataMsg);
      if (json !== "{}") {
        this.form.open_week = this.dataMsg.open_week.split(",");
        let arr = this.dataMsg.open_time.split(",");
        arr.forEach(ele => {
          ele = ele.split("-");
          this.form.open_time.push({ start: ele[0], end: ele[1] });
        });
      } else {
        this.form.open_week = [];
        this.form.open_time = [];
      }
      this.form.time = "";
      this.dialogVisible = false;
    },
    handleSubmit() {
      if (this.form.open_week.length <= 0) {
        this.$message.error("请选择营业日");
        return;
      }
      if (this.form.open_time.length <= 0) {
        this.$message.error("请选择时间段");
        return;
      }
      this.form.open_week.sort();
      this.dialogVisible = false;
    },
    addTime() {
      if (this.form.time) {
        if (this.form.open_time.length > 0) {
          let v = this.form.time[0].replace(/:/g, "");
          let t = this.form.open_time[length - 1].end.replace(/:/g, "");
          if (parseInt(v) < parseInt(t)) {
            this.$message.error("新添加时间段不能早于已添加时间段内");
            return;
          }
        }
        this.form.open_time.push({
          start: this.form.time[0],
          end: this.form.time[1]
        });
      } else {
        this.$message.error("请选择时间段");
      }
      this.form.time = "";
    },
    timeDel(i) {
      this.form.open_time.splice(i, 1);
    },
    async getAddress(obj) {
      await THREELEVELLINKAGE(obj).then(res => {
        let { code, data, msg } = res;
        if (code === 200) {
          this.options = data;
          if (this.pageName === "编辑门店") {
            this.cascaderTag(this.form.position, "edit");
          }
        } else {
          this.$message.error(msg);
        }
      });
    },
    cascaderTag(e, type) {
      let oneName, twoName, threeName;
      if (e[0]) {
        this.options.forEach(ele => {
          if (ele.id === e[0]) {
            oneName = ele.name;
          }
          if (e[1]) {
            ele.children.forEach(eles => {
              if (eles.id === e[1]) {
                twoName = eles.name;
              }
              if (e[2]) {
                eles.children.forEach(eless => {
                  if (eless.id === e[2]) {
                    threeName = eless.name;
                  }
                });
              }
            });
          }
        });
      }

      this.addressJson = { oneName, twoName, threeName };
      this.searchs = "";
      if (type === "edit") {
        this.searchTag();
      } else {
        this.form.address = "";
      }
    },
    searchTag() {
      this.form.longitude = "";
      this.form.latitude = "";
      this.form.selectAddress = "";
      this.addressJson.oneName
        ? (this.searchs = this.addressJson.oneName)
        : this.$message.error("选择地区后才可搜索");
      if (this.addressJson.twoName) this.searchs += this.addressJson.twoName;
      if (this.addressJson.threeName)
        this.searchs += this.addressJson.threeName;
      this.form.positions = this.searchs;
      this.searchs += this.form.address;
    },
    retunrData(e) {
      if (e) {
        this.form.selectAddress = e.address;
        this.form.longitude = e.lng;
        this.form.latitude = e.lat;
      }
    },
    inputTagMobile(e) {
      this.form.mobile = e;
    },
    inputTagUsername(e) {
      this.form.username = e;
    },
    out() {
      this.shows = "form";
    },
    async submit() {
      await this.$refs["form"].validate(valid => {
        if (valid) {
          let openTime = [];
          this.form.open_time.forEach(ele => {
            openTime.push(ele.start + "-" + ele.end);
          });
          ADD_STORE({
            name: this.form.name,
            store_number: this.form.store_number,
            username: this.form.username,
            truename: this.form.truename,
            mobile: this.form.mobile,
            open_week: this.form.open_week.join(","),
            open_time: openTime.join(","),
            position: this.form.position.join(","),
            address: this.form.address,
            select_address: this.form.selectAddress,
            province: this.form.position[0],
            city: this.form.position[1],
            area: this.form.position[2],
            longitude: this.form.longitude,
            latitude: this.form.latitude,
            status: this.form.status,
            tag_id: this.form.tag_id,
            store_id: this.dataMsg.store_id,
            sort: this.form.sort
          }).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.$emit("out");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        }
      });
      // if (!e) {
      //   this.$refs['form'].validate((valid) => {
      //     if (valid) {
      //       this.shows = 'set'
      //     }
      //   })
      // } else {
      // let openTime = []
      // this.form.open_time.forEach(ele => {
      //   openTime.push(ele.start + '-' + ele.end)
      // })
      //   await ADD_STORE({
      //     name: this.form.name,
      //     store_number: this.form.store_number,
      //     username: this.form.username,
      //     truename: this.form.truename,
      //     mobile: this.form.mobile,
      //     open_week: this.form.open_week.join(','),
      //     open_time: openTime.join(','),
      //     position: this.form.position.join(','),
      //     address: this.form.address,
      //     province: this.form.position[0],
      //     city: this.form.position[1],
      //     area: this.form.position[2],
      //     longitude: this.form.longitude,
      //     latitude: this.form.latitude,
      //     status: this.form.status,
      //     tag_id: this.form.tag_id,
      //     store_price: e.store_price,
      //     store_stock: e.store_stock,
      //     wq_manage: e.wq_manage,
      //     store_distribution: e.store_distribution,
      //     apply_yourself: e.apply_yourself,
      //     store_kefu: e.store_kefu
      //   }).then(res => {
      //     let { code, msg } = res
      //     if (code === 200) {
      //       this.$emit('out')
      //     }
      //     this.$message({
      //       message: msg,
      //       type: code === 200 ? 'success' : 'error'
      //     })
      //   })
      // }
    },
    async getLabel() {
      await STORE_TAGLIST({
        page: 1,
        pageshow: 100000
      }).then(res => {
        let { code, data } = res;
        if (code === 200) this.optionsLabel = data.list;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.dialogBox div {
  height: 36px;
  .timeC {
    width: 80%;
    display: flex;
    margin-top: 10px;
    .time-chlid {
      width: 130px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      background: #c0c4cc;
      position: relative;
      margin: 0 10px 10px 0;
      &:hover .time-del {
        display: inline-block;
      }
      .time-del {
        position: absolute;
        top: 3px;
        right: 3px;
        color: #f56c6c;
        cursor: pointer;
        display: none;
      }
    }
  }
}
.timeC {
  width: 80%;
  display: flex;
  margin-top: 10px;
  .time-chlid {
    width: 130px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    background: #c0c4cc;
    position: relative;
    margin: 0 10px 10px 0;
  }
}
</style>
